import tkinter as tk
from tkinter import filedialog, messagebox
from datetime import datetime
from PIL import Image, ImageTk
from tkcalendar import DateEntry
import json
import os
import re
from .OS import *



def create_card_dialog(window,columns,frames,DATA_FILE):
    dialog = tk.Toplevel(window)
    dialog.title("Create New Task")
    dialog.geometry("400x300")

    task_name_var = tk.StringVar()
    priority_var = tk.StringVar(value="High")
    due_date_var = tk.StringVar(value=datetime.now().strftime('%Y-%m-%d'))
    image_path_var = tk.StringVar()

    task_name_label = tk.Label(dialog, text="Task Name:")
    task_name_label.pack(pady=5)
    task_name_entry = tk.Entry(dialog, textvariable=task_name_var)
    task_name_entry.pack(pady=5)

    priority_label = tk.Label(dialog, text="Priority:")
    priority_label.pack(pady=5)
    priority_options = ["High", "Medium", "Low"]
    priority_menu = tk.OptionMenu(dialog, priority_var, *priority_options)
    priority_menu.pack(pady=5)

    due_date_label = tk.Label(dialog, text="Due Date (YYYY-MM-DD):")
    due_date_label.pack(pady=5)
    due_date_entry = DateEntry(dialog, textvariable=due_date_var, date_pattern='yyyy-mm-dd')
    due_date_entry.pack(pady=5)

    def select_image():
        try:
            filename = filedialog.askopenfilename(title="Select Image", filetypes=[("Image Files", "*.png;*.jpg;*.jpeg;*.gif")])
            if filename:
                image_path_var.set(filename)
        except Exception as e:
            messagebox.showerror("Image Selection Error", str(e))

    def on_confirm(columns,frames,DATA_FILE,window):
        if not task_name_var.get() or not priority_var.get() or not due_date_var.get():
            messagebox.showerror("Input Error", "All fields are required.")
            return
        add_task(task_name_var.get(), priority_var.get(), due_date_entry.get_date().strftime('%Y-%m-%d'), image_path_var.get(), dialog,columns,frames,DATA_FILE,window)

    confirm_button = tk.Button(dialog, text="Confirm", command=lambda:on_confirm(columns,frames,DATA_FILE,window))
    confirm_button.pack(pady=10)
    select_image_button = tk.Button(dialog, text="Select Image", command=select_image)
    select_image_button.pack(pady=5)
